<template>
<!--  @ok="handleSubmit"-->
  <BasicModal
    v-bind="$attrs"
    @register="register"
    showFooter
    :title="getTitle"
    width="75%"
    :showCancelBtn="false"
    :showOkBtn="false"
  >
    <!--    <BasicForm @register="registerForm"> </BasicForm>-->
    <!--    :label-col="labelCol"-->
    <!--    :wrapper-col="wrapperCol"-->
    <Form
      :model="formData"

      label-align="right"
      ref="formRef"
    >
      <div v-for="(item, index) in formSchemaList">
        <Divider v-if="item.component === 'divider'">{{ item.label }}</Divider>

        <FormItem
          v-bind="item"
          v-if="item.component"
          :name="item.field"
          v-show="(item.show != undefined && item.show) || item.show == undefined"
        >
          <Input
            v-if="item.component === 'Input'"
            :placeholder="'请输入' + item.label"
            v-model:value="formData[item.field]"
          ></Input>
          <InputNumber
            v-if="item.component === 'InputNumber'"
            :placeholder="item.placeholder ? item.placeholder : '请输入' + item.label"
            v-model:value="formData[item.field]"
          ></InputNumber>

          <div v-if="item.items" style="display: flex">
            <!--            -->
            <!--              :class="{ 'ant-col': true,-->
            <!--               'ant-col-14': true,-->
            <!--              'item-row': true }"  m_w_100-->
            <FormItem
              :labelCol="{span:6}"
              v-for="(item2, index2) in item.items"
              v-bind="item2"
              v-show="(item2.show != undefined && item2.show) || item2.show == undefined"
              :name="item2.field"
              :class="{ 'ant-col': true,
                           'ant-col-10': item.items.length==2,
                           'ant-col-8': item.items.length===3,
                           'm_w_100': item.items.length==1,
                          'item-row': true }"
            >
              <Switch
                v-if="item2.component === 'Switch'"
                :placeholder="item2.placeholder ? item2.placeholder : '请输入' + item2.label"
                v-model:checked="formData[item2.field]"
                @change="switchChangeFn"
              ></Switch>
              <Input
                v-if="item2.component === 'Input'"
                :placeholder="item2.placeholder ? item2.placeholder : '请输入' + item2.label"
                v-model:value="formData[item2.field]"
              ></Input>
              <InputNumber
                v-if="item2.component === 'InputNumber'"
                :placeholder="'请输入' + item2.label"
                v-model:value="formData[item2.field]"
                :name="item2.field"
              ></InputNumber>

              <Select
                v-if="item2.component === 'Select'"
                :placeholder="'请选择' + item2.label"
                v-model:value="formData[item2.field]"
                v-bind="item2.componentProps"
                @change="
                  (v, o) => {
                    return returnTypeChange(v, o, item2.field);
                  }
                "
              ></Select>

              <BasicUpload v-if="item2.component === 'Upload'"
                           :placeholder="'请选择' + item2.label"
                           v-model:value="formData[item2.field]"
                           v-bind="item2.componentProps"></BasicUpload>
              <!--    规格-->

            </FormItem>
          </div>
        </FormItem>
      </div>
    </Form>
  </BasicModal>
</template>
<script lang="ts" setup>
import {ref, computed, unref} from 'vue';
import {BasicForm, useForm} from '@/components/Form';
import {formSchema} from './role.data';
import {BasicModal, useModalInner} from '@/components/Modal';

import {BasicTree, TreeItem} from '@/components/Tree';
import {saveProductApi, productDetailApi, getNoApi, saveSkuApi} from '@/api/sys/wmProduct';
import {
  Form,
  FormItem,
  Input,
  InputNumber,
  DatePicker,
  Select,
  Switch,
  Divider
} from 'ant-design-vue';
import {BasicUpload, ImageUpload} from '@/components/Upload';
import {useMessage} from '@/hooks/web/useMessage';
import {useRefs} from '@vben/hooks';
import util from "@/utils/util";

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);
const {refs, setRefs} = useRefs();

const {createMessage} = useMessage();

const formSchemaList = ref(formSchema)
const formData = ref({});
const labelCol = ref({span: 10});
const wrapperCol = ref({span: 13});
const formRef = ref();

const id = ref('');
const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 90,
  baseColProps: {span: 24},
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [register, {setModalProps, closeModal}] = useModalInner(async (data) => {
  //打开弹层后的回调
  setModalProps({confirmLoading: false});
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  // if (unref(treeData).length === 0) {
  //   treeData.value = (await getMenuList()) as any as TreeItem[];
  // }
  isUpdate.value = data?.isUpdate;

  id.value = '';
  if (unref(isUpdate)) {
    // console.log("---data.record:",data.record)
    id.value = data.record.id;
    productDetailApi({
      prodId: id.value,
    }).then((res) => {
      //console.log(res)
      if (res.code == 200) {
        getBooksFn(res.data);
      }
    });
    // setFieldsValue({
    //   ...data.record,
    // });
  } else {
    getNoApi({type: "product"}).then((res) => {
      //console.log(res)
      if (res.code == 200) {
        formData.value = {
          prodNumber: res.data,
          isPostage: 1,
          // isPostageValue: true,
        };
      }
    });

  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增商品信息' : '编辑商品信息'));


async function handleSubmit() {
  try {

    // let productSpecFormRef = refs.value[0];

    // productSpecFormRef.submitFn();
    formRef.value
      .validate()
      .then(() => {


        setModalProps({confirmLoading: true});
        const values =unref(formData.value)  ;
        let skuObj=util.copy(values.skuObj) ;
        delete values.skuObj;
        delete values.wmProductSkuList;
        if (values.isPostageValue) {
          //如果是包邮的话要清空邮费
          values.presellPrice = null;
        }
        // TODO custom api
        values.id = id.value;

        // console.log(values);
        // return;
        //保存

        if (values.picArr) {
          values.pic = values.picArr.join(',');
        }
        if (values.picsArr) {
          values.pics = values.picsArr.join(',');
        }
        if (values.details) {
          values.detail = values.details.join(',');
        }
        saveProductApi(values)
          .then((res) => {
            // console.log("---res::",res)
            saveSkuApi({
              productId: res.data,
              productSkuList: skuObj.productSkuList,
              productSpecList: skuObj.productSpecList
            })
              .then((res) => {
                closeModal();
                emit('success');
                createMessage.success(res.message);

              })
          })
          .catch((res) => {
            createMessage.error(res.message);

          })
          .finally(() => {

          });
      }).catch((error) => {
      console.log('error', error);

    });


  } finally {
    setModalProps({confirmLoading: false});
  }
}

function getBooksFn(data) {
  let item=data.product;
  if (item.pic) {
    item.picArr = item.pic.split(',');
  } else {
    item.picArr = [];
  }
  if (item.pics) {
    item.picsArr = item.pics.split(',');
  } else {
    item.picsArr = [];
  }
  if (item.detail) {
    item.details = item.detail.split(',');
  } else {
    item.details = [];
  }


  //console.log("---item:",item)
  // setFieldsValue(item);
  formData.value = item;
  if(util.isNotEmpty(data.productSkuList)){
    data.productSkuList.forEach(r=>{
      if(util.isNotEmpty(r.wmSkuSpecList)){
        r.wmSkuSpecList.forEach(x=>{
          r[x.specGroupName]=x.specName;
        })
      }
    })
  }
  formData.value.skuObj={
    productSkuList:data.productSkuList,
    productSpecs:data.productSpecs
  }


}


function switchChangeFn(v, o, field) {
  // console.log(v, o, field)
}

function returnTypeChange(v, o, field) {

}

function productSpecSuccessFn(data) {
  console.log("--接收",data);
  formData.value.skuObj=data;
  // formData.value.productSpecList = data.productSpecList;
  // formData.value.productSkuList = data.productSkuList;
  handleSubmit()
}


</script>

<style lang="less">

.m_w_100 {
  width: 90%;

  .ant-col-6 {
    flex: 0 0 10%;
    max-width: 10%;
  }
}

.ant-form {
  .ant-form-item {
    margin-bottom: 10px;
  }
}
</style>
